import logging
import smtplib
import traceback
import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from app.config import settings

from msal import ConfidentialClientApplication


def send_email(email: str, body: str):
    try:
        msg = MIMEMultipart()
        msg["From"] = settings.from_email
        msg["To"] = email
        msg["Subject"] = "Document Conversion Notification"
        msg.attach(MIMEText(body, "plain"))

        with smtplib.SMTP(settings.smtp_server, settings.smtp_port) as server:
            server.starttls()
            server.login(settings.smtp_username, settings.smtp_password)
            server.send_message(msg)
    except Exception as e:
        logger = logging.getLogger(__name__)
        logger.error(f"Send email failed: {repr(e)}")
        logger.error(traceback.format_exc())
        raise


# 🔑 配置
# TENANT_ID = "0696a879-d866-4aa1-bc14-8d1d96ee08a3"
# CLIENT_ID = "44d1f295-3622-4ece-83ac-0e13ffb81a27"
# CLIENT_SECRET = "UAl8Q~E-IY4HtBBkh654QOk_y8jfV6EucdmwXds7"
# SENDER_EMAIL = "peicai.li@techtanium.com"  # 发件人邮箱（必须在租户里）
# RECIPIENT_EMAIL = "xiaoxiang.cai@techtanium.com"  # 收件人邮箱


def get_token():
    app = ConfidentialClientApplication(
        settings.techtanium_client_id,
        authority=f"https://login.microsoftonline.com/{settings.techtanium_tenant_id}",
        client_credential=settings.techtanium_client_secret,
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    if "access_token" not in token:
        raise Exception(f"Get token failed: {token}")
    return token["access_token"]


def list_tenant_emails(access_token):
    headers = {"Authorization": f"Bearer {access_token}"}
    url = "https://graph.microsoft.com/v1.0/users?$select=mail,userPrincipalName&$top=999"
    resp = requests.get(url, headers=headers)
    if resp.status_code != 200:
        raise Exception(f"Failed to list users: {resp.status_code}, {resp.text}")
    users = resp.json().get("value", [])
    emails = [u["mail"] for u in users if u.get("mail")]
    return emails


def send(access_token, sender_email, to_email, subject, body):
    headers = {"Authorization": f"Bearer {access_token}"}
    url = f"https://graph.microsoft.com/v1.0/users/{sender_email}/sendMail"
    payload = {
        "message": {
            "subject": subject,
            "body": {"contentType": "Text", "content": body},
            "toRecipients": [{"emailAddress": {"address": to_email}}],
        }
    }
    resp = requests.post(url, headers=headers, json=payload)
    return resp.status_code, resp.text


def send_email_to_techtanium(email: str, body: str):
    access_token = get_token()
    emails = list_tenant_emails(access_token)
    print("Tenant emails:", emails)

    if settings.techtanium_sender not in emails:
        print(f"❌ SENDER_EMAIL '{settings.techtanium_sender}' is not a valid tenant email")
        return

    status, response = send(
        access_token,
        settings.techtanium_sender,
        email,
        "Document Conversion Notification  ✅",
        body
    )
    print("Status:", status)
    print("Response:", response)
